package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * ID生成器
 */
@Component
public class RedisIdWorker {

    private static final long BEGIN_TIMESTAMP = 1704067200L; //起始时间戳，即2024一月一日零时零分零秒对应的秒数
    private static final int COUNT_BITS = 32; //序列号位数

    private StringRedisTemplate redisTemplate;

    public RedisIdWorker(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public long nextId(String keyPrefix) {
        //1. 生成时间戳
        LocalDateTime nowDateTime = LocalDateTime.now();
        long nowSecond = nowDateTime.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;
        //2. 生成序列号
        //key由前缀icr、keyPrefix、当前年月日拼接而成，可以有效避免自增长溢出
        String datePrefix = nowDateTime.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long count = redisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + datePrefix);
        //3. 拼接并返回
        return (timestamp << COUNT_BITS) | count;
    }

//    public static void main(String[] args) {
//        LocalDateTime localDateTime = LocalDateTime.of(2024, 1, 1, 0, 0, 0);
//        long epochSecond = localDateTime.toEpochSecond(ZoneOffset.UTC);
//        System.out.println(epochSecond);
//    }
}
